<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 15-9-18
 * Time: 下午4:58
 */
class SupplyController extends Controller {

    private $_title;

    public function init() {
        parent::init();
        // 取得用户信息
        $user_info = $this->_session->offsetGet ( 'loginInfos' );
        $this->_view->userInfo=$user_info;
    }

    //供应商列表
    public function indexAction(){
        global $_getAreaNames,$_PublishTimeCfg;
        define ( 'ITEM_PER_PAGE', 10 );
        $this->_title = '供应商报价';
        $this->_keywords = '供应商报价';
        $this->_description = '供应商报价';
        $url = "/supply/index";
        $nowtime = date('Y-m-d H:i:s' ,strtotime('now'));
        //分类
        $index = new IndexModel();
        $cate = $index->getCateInfo("cate",'','');
        //实例化当前module
        $Supply = new SupplyModel();

        //获取筛选参数
        $kd=empty($_GET['kd']) ? '' :htmlspecialchars(trim($_GET['kd']) , ENT_QUOTES ,'utf-8');

        $page=empty($_GET['page']) ? 1 :htmlspecialchars(trim($_GET['page']) , ENT_QUOTES ,'utf-8');

        $cate_name=empty($_GET['cate_name']) ? '' :htmlspecialchars(trim($_GET['cate_name']) , ENT_QUOTES ,'utf-8');

        $cates_name=empty($_GET['cates_name']) ? '' :htmlspecialchars(trim($_GET['cates_name']) , ENT_QUOTES ,'utf-8');

        $area_id=empty($_GET['area_id']) ? '' :htmlspecialchars(trim($_GET['area_id']) , ENT_QUOTES ,'utf-8');

        $area_name=empty($_GET['area_name']) ? '' :htmlspecialchars(trim($_GET['area_name']) , ENT_QUOTES ,'utf-8');

        $product_name=empty($_GET['product_name']) ? '' :htmlspecialchars(trim($_GET['product_name']) , ENT_QUOTES ,'utf-8');

        $brand_name=empty($_GET['brand_name']) ? '' :htmlspecialchars(trim($_GET['brand_name']) , ENT_QUOTES ,'utf-8');

        $business_name=empty($_GET['business_name']) ? '' :htmlspecialchars(trim($_GET['business_name']) , ENT_QUOTES ,'utf-8');

        $orderby=empty($_GET['order']) ? '' :htmlspecialchars(trim($_GET['order']) , ENT_QUOTES ,'utf-8');

        $list_search=empty($_GET['list_search']) ? '' :htmlspecialchars(trim($_GET['list_search']) , ENT_QUOTES ,'utf-8');


        $publish_time=empty($_GET['publish_time']) ? '' :htmlspecialchars(trim($_GET['publish_time']) , ENT_QUOTES ,'utf-8');


        $condition = array();
        $conditions = array();
        $urls=array();

        if(!empty($cate_name)){
            $conditions[] = "product_cates.cate_name like '%{$cate_name}%'";
            $urls[]="cate_name={$cate_name}";
        }

        if(!empty($area_id)){
            $conditions[] = "iq_quotation.area_id = '{$area_id}'";
            $urls[]="area_id={$area_id}";
        }

        if(!empty($area_name)){
            $conditions[] = "region.region_name = '{$area_name}'";
            $urls[]="area_name={$area_name}";
        }
        $keyword_list_search=strtr($list_search, array('%'=>'\%'));
        if(!empty($list_search)){
            $conditions[] =" (product.product_name like '%{$keyword_list_search}%' or product_cates.cate_name like '%{$keyword_list_search}%' or product_brands.brand_name like '%{$keyword_list_search}%' or region.region_name like '%{$keyword_list_search}%' or iq_quotation.delivery_area like '%{$keyword_list_search}%')";
            $urls[]="list_search={$list_search}";
        }

        if(!empty($product_name)){
            $conditions[] = "product.product_name like '%{$product_name}%'";
            $urls[]="product_name={$product_name}";
        }

        if(!empty($brand_name)){
            $conditions[] = "product_brands.brand_name like '%{$brand_name}%'";
            $urls[]="brand_name={$brand_name}";
        }

        if(!empty($business_name)){
            $conditions[] = "users_invoice.business_name like '%{$business_name}%'";
            $urls[]="business_name={$business_name}";
        }


        $having = "1=1";

        if(!empty($publish_time)){
            if($publish_time==6){
                //30天内
                $end = $nowtime;
                $start = date('Y-m-d H:i:s' ,strtotime('-1 month'));
            }else if($publish_time==5){
                //15天内
                $end = $nowtime;
                $start = date('Y-m-d H:i:s' ,strtotime('-15 day'));
            }else if($publish_time==4){
                //10天内
                $end = $nowtime;
                $start = date('Y-m-d H:i:s' ,strtotime('-10 day'));
            }else if($publish_time==3){
                //5天内
                $end = $nowtime;
                $start = date('Y-m-d H:i:s' ,strtotime('-5 day'));
            }else if($publish_time==2){
                //3天内
                $end = $nowtime;
                $start = date('Y-m-d H:i:s' ,strtotime('-3 day'));
            }else{
                //1天内
                $end = $nowtime;
                $start = date('Y-m-d H:i:s' ,strtotime('-1 day'));
            }

            $having .= " and max(iq_quotation.update_time) >= '{$start}'";
            $having .= " and max(iq_quotation.update_time) <= '{$end}'";
            $urls[]="publish_time='{$publish_time}'";
        }




        $url .= "?page=%d";
        $where= "1=1";
        $wheres= "1=1";

        if(empty($conditions))
        {
            $wheres  .= " AND iq_quotation.business_id <> ''  AND  users_invoice.main_variety <> '' AND users_invoice.business_name<>''";
        } else {
            $wheres  .= " AND iq_quotation.business_id <> ''  AND  users_invoice.main_variety <> '' AND users_invoice.business_name<>''"." AND ".implode(' AND ', $conditions);
        }

        //下面或者关系
        if(!empty($cates_name)){
            $condition[]= "product_cates.cate_name like '%{$cates_name}%'";
            $urls[]="cates_name={$cates_name}";
        }

        if(empty($condition))
        {
            $where  = '1=1 ';
        } else {
            $where  .= " AND ".implode(' AND ', $condition);
        }

        if(!empty($condition)){
            if(!empty($cate_name)){
                $wheres.= " or (".$where.")";
            }else{
                $wheres.= " AND (".$where.")";
            }
        }

        if(!empty($urls)){
            $url.=  "&".implode('&',$urls);
        }

        $url.="&order={$orderby}";

        //这边去加载首页的数据
        if($orderby=='visitdesc'){
            $order = "users_invoice.visit desc";
        }else{
            $order = "max(iq_quotation.update_time) desc";
        }

        $group = "`users_invoice`.`id`";

        #####################################################
        $search = new SearchModel();
        //这边还是要去查询地区
        $AreaShow = $search->getAreaShow("iq.area_id <> '' and iq.status = '2' ");

        if(!empty($AreaShow)){
            foreach($AreaShow as $key=>$var){
                if(!empty($var['area_id']) && !empty($var['area_name'])){
                    $areas[] =  $var['area_id'];
                }
                unset($AreaShow[$key]);
            }
        }
        if(!empty($areas)){
            $AreaShow = array_unique($areas);
        }

        $Region =   new RegionModel();
        if(!empty($AreaShow)){
            foreach($AreaShow as $k=>$v){
                $AreaShowLIst[$k]['area_id'] = $v;
                $AreaShowLIst[$k]['area_name'] = $Region->getOneByIdAndName($v,"region_name");
            }
        }else{
            $AreaShowLIst = array();
        }

        $CountArea = count($AreaShowLIst);

        #######################################################

        $totalItems =  $Supply->getSupplyTatolWhere($wheres,$group,$having);
        $offset = 0;
        $page =  empty($page) ? 1 :$page;
        $offset = ($page - 1) * ITEM_PER_PAGE;
        if ($offset >= $totalItems) {
            $page = ceil ( $totalItems / ITEM_PER_PAGE );
            $offset = ($page - 1) * ITEM_PER_PAGE;
        }
        if ($offset < 0) {
            $offset = 0;
            $page = 1;
        }

        $data = $Supply->getSupplyListByWhere($wheres,ITEM_PER_PAGE,$offset,$order,$group,$having);

        $links = Pagination::createPage($url, ITEM_PER_PAGE, $page, $totalItems, 2 ,'_self',true);
        $linkpage = Tools::linkPage($url,  ITEM_PER_PAGE, $page, $totalItems, $target = '_self');


        $this->_view->title = $this->_title;
        $this->_view->keywords  = $this->_keywords;
        $this->_view->description = $this->_description;
        $this->_view->_getAreaNames = $_getAreaNames;
        $this->_view->cate = $cate;
        $this->_view->kd = $kd;
        $this->_view->AreaShowLIst = $AreaShowLIst;
        $this->_view->CountArea = $CountArea;

        $this->_view->totalItems = $totalItems;
        $this->_view->data = $data;
        $this->_view->links = $links;
        $this->_view->linkpage = $linkpage;

        $this->_view->cate_name = $cate_name;
        $this->_view->cates_name = $cates_name;
        $this->_view->area_id = $area_id;
        $this->_view->area_name = $area_name;
        $this->_view->product_name = $product_name;
        $this->_view->brand_name = $brand_name;
        $this->_view->business_name = $business_name;
        $this->_view->list_search = $list_search;
        $this->_view->order = $orderby;
        $this->_view->_PublishTimeCfg = $_PublishTimeCfg;
        $this->_view->publish_time = $publish_time;

    }
    //这边是报价单列表
    public function supplylistAction(){
        global $_getAreaNames;
        define ( 'ITEM_PER_PAGE', 20 );
        $this->_title = '供应商报价';
        $this->_keywords = '供应商报价';
        $this->_description = '供应商报价';
        $url = "/supply/supplylist";
        $nowtime = date('Y-m-d H:i:s' ,strtotime('now'));
        //分类
        $index = new IndexModel();
        $cate = $index->getCateInfo("cate",'','');
        //实例化当前module
        $Supply = new SupplyModel();
        //获取参数
        $kd=empty($_GET['kd']) ? '' :htmlspecialchars(trim($_GET['kd']) , ENT_QUOTES ,'utf-8');
        $page=empty($_GET['page']) ? 1 :htmlspecialchars(trim($_GET['page']) , ENT_QUOTES ,'utf-8');
        //获取公司的id
        $id=empty($_GET['id']) ? '0' : (int)$_GET['id'];
        //这边判断id是否存在
        if(empty($id)){
            $this->redirect('/error/error404?error=公司获取失败');
            die();
        }
        //这边判断￥id是否正确
        $busi_info = $Supply->getListById($id);
        if(empty($busi_info)){
            $this->redirect('/error/error404?error=公司信息不存在');
            die();
        }
        $quote = new QuotationModel();
        $where  =  "iq_quotation.business_id = '{$id}'";
        $url .= "?page=%d&id={$id}";
        $totalItems =  $quote->getQuoteCountByWhere($where);
        $offset = 0;
        $page =  empty($page) ? 1 :(int)$page;
        $offset = ($page - 1) * ITEM_PER_PAGE;
        if ($offset >= $totalItems) {
            $page = ceil ( $totalItems / ITEM_PER_PAGE );
            $offset = ($page - 1) * ITEM_PER_PAGE;
        }
        if ($offset < 0) {
            $offset = 0;
            $page = 1;
        }
        $order="iq_quotation.update_time desc";
        $group="";
        $supply_info = $quote->getQuoteListByWhere($where,ITEM_PER_PAGE,$offset,$order,$group);

        $links = Pagination::createPage($url, ITEM_PER_PAGE, $page, $totalItems, 2 ,'_self',true);

        $link_url = Tools::linkPage($url,  ITEM_PER_PAGE, $page, $totalItems, $target = '_self');

        $this->_view->title = $this->_title;
        $this->_view->keywords  = $this->_keywords;
        $this->_view->description = $this->_description;
        $this->_view->_getAreaNames = $_getAreaNames;
        $this->_view->cate = $cate;
        $this->_view->kd = $kd;
        $this->_view->busi_info = $busi_info;

        $this->_view->links = $links;
        $this->_view->link_url = $link_url;
        $this->_view->supply_info = $supply_info;
    }
    //这边是下载供应报价单
    public function downsupplyAction(){
        ob_clean();
        $nowtime = date('Y-m-d H:i:s' ,strtotime('now'));
        $business_id = empty($_GET['id']) ? 1 :(int)htmlspecialchars(trim($_GET['id']) , ENT_QUOTES ,'utf-8');
        //实例化当前module
        $quote = new QuotationModel();
        $start_time = date('Y-m-d 00:00:00' ,strtotime('now'));
        $end_time = $nowtime;
        if(empty($business_id)){
            $this->redirect('/error/error404?error=公司获取失败');
            die();
        }
        $Supply = new SupplyModel();
        //这边判断￥id是否正确
        $busi_info = $Supply->getListById($business_id);
        if(empty($busi_info)){
            $this->redirect('/error/error404?error=公司信息不存在');
            die();
        }
        $where = "iq_quotation.business_id = '{$business_id}' and iq_quotation.update_time>='{$start_time}' and iq_quotation.update_time<='{$end_time}'";
        $feild=array(
            'id',
            'business_name',
            "cate_name",
            "product_name",
            "brand_name",
            "service_name",
            "price",
            "currency_id",
            "settlement",
            "num",
            "delivery_method",
            "delivery_area",
            "delivery_time",
        );

        $quote_list = $quote->getDownList($where);

        $excelHeadData = array (
            "business_name" => "供应商名称",
            "cate_name" => "品种",
            "product_name" => "牌号",
            "brand_name" => "厂商",
            "service_name" => "交易类型",
            "price" => "价格(元/吨)",
            "currency_name" => "币种",
            "settlement" => "结算方式",
            "num" => "数量(吨)",
            "delivery_method" => "提货方式",
            "delivery_area" => "交货地点",
            "delivery_time" => "交货时间",
        );

        $phpExcel = new PHPExcel ();
        // 读取模版
        $saleFile = "excelModel/downquote.xls";
        $PHPReader = new PHPExcel_Reader_Excel5 ();
        if ($PHPReader->canRead ( $saleFile )) {
            $phpExcel = $PHPReader->load ( $saleFile );
        }
        // 定义输出的表名
        $filename = "供应商报价表" . date ( "YmdHis" ) . ".xls";
        // 设置字体颜色为红色
        $styleFontColorRed = array (
            "font" => array (
                "color" => array (
                    "argb" => "FFFF0000"
                )
            )
        );
        // 设置表头
        $key = ord ( "A" );
        foreach ( $excelHeadData as $key1 => $value ) {
            $colum = chr ( $key );
            $phpExcel->setActiveSheetIndex ( 0 )->setCellValue ( $colum . '1', $value );
            $key += 1;
        }
        // 循环读入数据的内容
        $column = 2;
        foreach ( $quote_list as $key1 => $val) {
            if(!empty($val['delivery_method'])){
                if($val['delivery_method']=='2'){
                    $val['delivery_method'] = "配送";
                }else{
                    $val['delivery_method'] = "自提";
                }
            }else{
                $val['delivery_method'] = "自提";
            }
            // 格式化存入的内容
            $excelData = array (
                "business_name" => $val['business_name'],
                "cate_name" => $val['cate_name'],
                "product_name" => $val['product_name'],
                "brand_name" => $val['brand_name'],
                "service_name" => $val['service_name'],
                "price" => $val['price'],
                "currency_name" => $val['currency_name'],
                "settlement" => $val['settlement'],
                "num" => $val['num'],
                "delivery_method" => $val['delivery_method'],
                "delivery_area" => empty($val['region_name'])? '':$val['region_name'],
                "delivery_time" => empty($val['delivery_time'])?'':$val['delivery_time'],
            ) ;
            // 设置内容数据
            $key = ord ( "A" );
            foreach ( $excelData as $key2 => $value2 ) {
                $colum = chr ( $key );
                //C行全部设置为文本型的数据
                if($colum =="C"){
                    $phpExcel->getActiveSheet()->setCellValueExplicit('C'.$column,$value2,PHPExcel_Cell_DataType::TYPE_STRING);
                }else{
                    $phpExcel->setActiveSheetIndex ( 0 )->setCellValue ( $colum . $column, $value2 );
                }
                // 状态为取消的时候设置为红色
//                if ("已取消" === $value2) {
//                    $phpExcel->getActiveSheet ()->getStyle ( $colum . $column )->applyFromArray ( $styleFontColorRed );
//                }
                $key += 1;
            }
            $column ++;
        }

        // 设置筛选 筛选一定是一个范围 如果是每列筛选 就筛选全表 从A1 到最后一列一行的结尾
        $phpExcel->getActiveSheet ()->setAutoFilter ( 'A1:T' . $column );
        $filename = iconv ( "utf-8", "gb2312", $filename );
        $obj_Writer = PHPExcel_IOFactory::createWriter ( $phpExcel, 'Excel5' );

        header ( "Content-Type: application/force-download" );
        header ( "Content-Type: application/octet-stream" );
        header ( "Content-Type: application/download" );
        header ( 'Content-Disposition:inline;filename="' . $filename . '"' );
        header ( "Content-Transfer-Encoding: binary" );
        header ( "Last-Modified: " . gmdate ( "D, d M Y H:i:s" ) . " GMT" );
        header ( "Cache-Control: must-revalidate, post-check=0, pre-check=0" );
        header ( "Pragma: no-cache" );
        $obj_Writer->save ( 'php://output' );
        exit ();

    }


}